package com.tzstcl.framework.config;

import com.tzstcl.framework.handler.WebSocketHandshakeHandler;
import com.tzstcl.framework.interceptor.WebSocketHandshakeInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.StompWebSocketEndpointRegistration;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * 配置基于STOMP的WebSocket
 **/
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    /**
     * 注册Stomp端点(指定webSocket的服务端),可注册多个
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        StompWebSocketEndpointRegistration webSocketServer = registry.addEndpoint("/webSocketServer");
        //跨域设置
        //webSocketServer.setAllowedOrigins("*");
        //添加握手拦截器
        webSocketServer.addInterceptors(new WebSocketHandshakeInterceptor());
        //设置握手处理器
        webSocketServer.setHandshakeHandler(new WebSocketHandshakeHandler());
        //支持socketJS访问
        webSocketServer.withSockJS();
    }

    /**
     * 配置消息代理,可配置多个
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //配置代理名称前缀为'/channel', 之后就可以向订阅'/channel'及'/channel**'的客户端推送消息
        registry.enableSimpleBroker("/channel");
        //配置请求地址前缀，所有以配置内容为前缀的消息请求地址都会路由到带有@MessageMapping或@SubscribeMapping注解的方法中
        //例如,客户端发送到/message/test的消息, 会被带@MessageMapping("/test")注解的方法处理
        registry.setApplicationDestinationPrefixes("/message");
        //配置点对点请求前缀
        registry.setUserDestinationPrefix("/point");

    }

    /**
     * 输入消息通道配置
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        //添加自定义实现ChannelInterceptor接口的消息拦截器
        //registration.interceptors(new WebSocketChannelInterceptor());
    }

    /**
     * 输出消息通道配置
     * @param registration
     */
    @Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {

    }

}
